package org.zjx.service;


import org.zjx.model.prop.ItemInstance;
import org.zjx.model.prop.ItemTemplate;
import org.zjx.repository.ItemTemplateRepository;

import java.util.Optional;

public class ItemStackService {
    private final ItemTemplateRepository templateRepository;

    public ItemStackService(ItemTemplateRepository templateRepository) {
        this.templateRepository = templateRepository;
    }

    public boolean canStack(ItemInstance item1, ItemInstance item2) {
        if (item1.getTemplateId() != item2.getTemplateId()) {
            return false;
        }

        Optional<ItemTemplate> templateOpt = templateRepository.findTemplateById(item1.getTemplateId());
        return templateOpt.isPresent() && templateOpt.get().isStackable();
    }

    public boolean handleStack(ItemInstance source, ItemInstance target) {
        Optional<ItemTemplate> templateOpt = templateRepository.findTemplateById(source.getTemplateId());
        if (!templateOpt.isPresent()) {
            return false;
        }

        int maxStack = templateOpt.get().getMaxStack();
        if (target.getDurability() >= maxStack) {
            return false;
        }

        int total = source.getDurability() + target.getDurability();
        if (total <= maxStack) {
            target.setDurability(total);
            source.setDurability(0);
        } else {
            target.setDurability(maxStack);
            source.setDurability(total - maxStack);
        }
        return true;
    }
}